// Copyright Epic Games, Inc. All Rights Reserved.

#if ZEN_WITH_TRACE

#	include <zencore/config.h>
#	include <zencore/zencore.h>

#	define TRACE_IMPLEMENT 1
#	include <zencore/trace.h>

void
TraceInit(std::string_view ProgramName)
{
	static std::atomic_bool gInited	 = false;
	bool					Expected = false;
	if (!gInited.compare_exchange_strong(Expected, true))
	{
		return;
	}

	trace::FInitializeDesc Desc = {
		.bUseImportantCache = true,
	};
	trace::Initialize(Desc);

#	if ZEN_PLATFORM_WINDOWS
	const char* CommandLineString = GetCommandLineA();
#	else
	const char* CommandLineString = "";
#	endif

	trace::ThreadRegister("main", /* system id */ 0, /* sort id */ 0);
	trace::DescribeSession(ProgramName,
#	if ZEN_BUILD_DEBUG
						   trace::Build::Debug,
#	else
						   trace::Build::Development,
#	endif
						   CommandLineString,
						   ZEN_CFG_VERSION_BUILD_STRING);
}

void
TraceShutdown()
{
	(void)TraceStop();
	trace::Shutdown();
}

bool
IsTracing()
{
	return trace::IsTracing();
}

void
TraceStart(std::string_view ProgramName, const char* HostOrPath, TraceType Type)
{
	TraceInit(ProgramName);
	switch (Type)
	{
		case TraceType::Network:
			trace::SendTo(HostOrPath);
			break;

		case TraceType::File:
			trace::WriteTo(HostOrPath);
			break;

		case TraceType::None:
			break;
	}
	trace::ToggleChannel("cpu", true);
}

bool
TraceStop()
{
	trace::ToggleChannel("cpu", false);
	if (trace::Stop())
	{
		return true;
	}
	return false;
}

#endif	// ZEN_WITH_TRACE
